using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 摄像机旋转
/// 玩家左右旋转控制实现左右移动
/// 摄像机上下旋转控制实现上下移动
/// </summary>
public class MouseLook : MonoBehaviour
{
    [Tooltip("视野灵敏度")]public float mouseSenstivity = 400f;
    private Transform playerBody;//玩家位置
    private float yRotation = 0f;//摄像机上下旋转的数值
    
    private CharacterController characterController;//玩家控制器
    [Tooltip("当前摄像机高度")]public float height = 1.8f;//摄像机初始高度
    private float interpolationSpeed = 12f;//摄像机平滑度
    
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        playerBody = transform.parent;
        characterController = playerBody?.GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSenstivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSenstivity * Time.deltaTime;
        
        //如果是手机端，则不进行鼠标控制
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            mouseSenstivity = 100f;
            //获取手机端的触控输入
            mouseX = Input.GetTouch(0).deltaPosition.x * mouseSenstivity * Time.deltaTime;
            mouseY = Input.GetTouch(0).deltaPosition.y * mouseSenstivity * Time.deltaTime;
        }
        

        yRotation -= mouseY;
        yRotation = Mathf.Clamp(yRotation, -60f, 60f);

        transform.localRotation = Quaternion.Euler(yRotation, 0f, 0f);//摄像机位置旋转
        playerBody.Rotate(Vector3.up * mouseX);//玩家位置旋转
        
        /**当人物下蹲或者站立的时候，随着高度变化，摄像机的高度也会变化*/
        float heightTarget = characterController.height * 0.9f;
        height = Mathf.Lerp(height, heightTarget, interpolationSpeed * Time.deltaTime);
        //设置摄像机的高度
        transform.localPosition = Vector3.up * height;
    }
    
}
